package com.shivandragon.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.shivandragon.utils.AuthorizationManager;
import com.shivandragon.utils.MongoSingletonHolder;
import com.shivandragon.utils.AuthorizationManager.Authorization;

public class PresentationsListController extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private AuthorizationManager authorizationManager = new AuthorizationManager();
	private MongoSingletonHolder mongoSingletonHolder = MongoSingletonHolder.getInstance();
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		if(!authorizationManager.getAuthorisation(request).equals(Authorization.ADMIN)) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;	
		}
		
		if("remove".equals(request.getParameter("action"))) {
			String idStr = request.getParameter("_id");
			mongoSingletonHolder.getPresentationsDBCollection().remove(new BasicDBObject("_id", new ObjectId(idStr)));
		}
		DBObject queryObj = new BasicDBObject();
		DBObject fieldsObj = new BasicDBObject("title", 1).append("creationDate", 1).append("_id", 1);
		DBObject sortObj = new BasicDBObject("creationDate", -1);
		List<DBObject> presentations = mongoSingletonHolder.getPresentationsDBCollection().find(queryObj, fieldsObj).sort(sortObj).toArray();
		if(presentations!=null) {
			request.setAttribute("presentationsCount", presentations.size());
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
			for(int i=0; i<presentations.size(); i++) {
				request.setAttribute("title"+i, presentations.get(i).get("title"));
				request.setAttribute("creationDate"+i, sdf.format(presentations.get(i).get("creationDate")));
				request.setAttribute("_id"+i, presentations.get(i).get("_id").toString());
			}
		} else {
			request.setAttribute("presentationsCount", 0);
		}
		request.getRequestDispatcher("/WEB-INF/presentationsList.jsp").forward(request, response);
	}
}
